package cn.steel.controller.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.domain.entity.MaterialReportAudit;
import cn.steel.domain.entity.Product;
import cn.steel.domain.entity.ProductOffShelfLog;
import cn.steel.domain.entity.User;
import cn.steel.domain.vo.ProductVo;
import cn.steel.mapper.ProductMapper;
import cn.steel.service.MaterialReportAuditService;
import cn.steel.service.ProductService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@Controller
@RequestMapping("/manager/product")
@Api(tags = "管理员商品管理")
@PreAuthorize("hasAuthority('ADMIN')")
@RequiredArgsConstructor
public class ManagerProductController {

    private final ProductService productService;
    private final MaterialReportAuditService auditService;
    private final ProductMapper productMapper;

    @ApiOperation("显示商品列表页面")
    @GetMapping
    public String productList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Integer status,
            Model model) {
        log.info("显示商品列表页面: page={}, size={}, search={}, categoryId={}, status={}", page, size, search, categoryId, status);
        PageHelper.startPage(page, size);
        Page<ProductVo> pageResult = productService.getProductsPaginated(search, null, categoryId, null, null, status);
        model.addAttribute("products", pageResult.getResult());
        model.addAttribute("totalPages", pageResult.getPages());
        model.addAttribute("totalItems", pageResult.getTotal());
        model.addAttribute("currentPage", pageResult.getPageNum());
        model.addAttribute("pageSize", size);
        model.addAttribute("search", search);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("status", status);
        model.addAttribute("categories", productService.getCategories());
        return "manager/product_manager_list";
    }
    @ApiOperation("显示商品审核页面")
    @GetMapping("/audit")
    public String auditProductForm(@RequestParam Long id, Model model) {
        log.info("显示商品审核页面: id={}", id);
        Product product = productService.getProductById(id);
        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        ProductVo productVo = BeanUtil.toBean(product, ProductVo.class);
        productVo.setCategoryName(productService.findCategoryById(product.getCategoryId()));
        model.addAttribute("product", productVo);
        return "manager/product_audit";
    }

    @ApiOperation("提交商品审核")
    @PostMapping("/audit")
    public String auditProduct(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam Long id,
            @RequestParam String status,
            @RequestParam(required = false) String auditComment) {
        log.info("提交商品审核: id={}, status={}, auditComment={}", id, status, auditComment);
        MaterialReportAudit audit = auditService.findByProductId(id);
        Product product = productService.getProductById(id);
        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        if (audit == null) {
            throw new IllegalArgumentException("材质报告审核记录不存在");
        }
        audit.setStatus(status);
        audit.setAuditComment(auditComment);
        audit.setAuditorId(user.getId());
        audit.setAuditTime(LocalDateTime.now());
        auditService.updateAudit(audit);

        if ("APPROVED".equals(status)) {
            product.setStatus(1); // 上架
        } else {
            product.setStatus(0); // 审核不通过，保持下架
        }
            product.setUpdateTime(LocalDateTime.now());
            productMapper.updateProduct(product);
        return "redirect:/manager/product";
    }

    @ApiOperation("下架商品")
    @PostMapping("/off-shelf")
    public String offShelfProduct(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam Long id,
            @RequestParam String reason) {
        log.info("下架商品: id={}, reason={}", id, reason);
        Product product = productService.getProductById(id);
        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        product.setStatus(0); // 下架
        product.setUpdateTime(LocalDateTime.now());
        productService.updateProduct(product, null, null);
        // 插入下架日志
        ProductOffShelfLog log = new ProductOffShelfLog();
        log.setProductId(id);
        log.setAdminId(user.getId());
        log.setReason(reason);
        log.setCreateTime(LocalDateTime.now());
        auditService.insertOffShelfLog(log);
        return "redirect:/manager/product";
    }
}